﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.SmartHealthcareZSJ;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.HospitalCommand;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.HospitalCommandHandler
{
    /// <summary>
    /// 医院创建命令处理类
    /// </summary>
    public class HospitalCreateCommandHandler : IRequestHandler<HospitalCreateCommand, APIResult<object>>
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly SqlSugarContext sugar;
        /// <summary>
        /// AutoMapper实例
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sugar"></param>
        /// <param name="mapper"></param>
        public HospitalCreateCommandHandler(SqlSugarContext sugar, IMapper mapper)
        {
            this.sugar = sugar;
            this.mapper = mapper;
        }


        /// <summary>
        /// 处理医院创建命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<object>> Handle(HospitalCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                //开启事务
                sugar.db.Ado.BeginTran();
                var model = mapper.Map<HospitalZ>(request);
                model.IsRecommended = request.IsRecommended;
                model.CreateName = request.CreateName;
                var r = await sugar.db.Insertable(model).ExecuteCommandAsync();
                if (r > 0)
                {
                    // 提交事务
                    sugar.db.Ado.CommitTran();
                    result.Code = APIEnum.添加成功;
                    result.Msg = APIEnum.添加成功.ToString();
                    result.data = r;
                }
                else
                {
                    // 回滚事务
                    sugar.db.Ado.RollbackTran();
                    result.Code = APIEnum.添加失败;
                    result.Msg = APIEnum.添加失败.ToString();
                    result.data = r;
                }


            }
            catch (Exception ex)
            {
                // 发生异常时回滚事务
                sugar.db.Ado.RollbackTran();
                // 记录异常信息
                Console.WriteLine($"添加慢病诊疗记录信息时发生异常: {ex.Message}");
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
                result.data = 0;
            }
            return await Task.FromResult(result);
        }
    }
}
